import { autoUpdater } from "electron-updater";
import * as log from "electron-log/main";
import { app, BrowserWindow } from "electron";

type ProcessType = {
    total: number;//要下载文件的总大小
    delta: number;//下载的增量，比上次大了多少
    percent: number;//下载的百分比
    bytesPerSecond: number;//下载速度
    transferred: number;//已经下载的文件大小
}

class UpdateTool {
    version: string = "";
    constructor() {
        this.version = app.getVersion();
        autoUpdater.setFeedURL('http://localhost:3010/download');
        autoUpdater.autoDownload = false;
    }
    checkUpdate() {
        log.info("checking update...");
        autoUpdater.on("update-available", this.available.bind(this));
        autoUpdater.checkForUpdates();
    }
    available(info: any) {
        log.info("available update...");
        autoUpdater.on('update-downloaded', this.downloaded.bind(this));
        autoUpdater.on('download-progress', this.progress.bind(this));
        //往渲染进程发送消息，由渲染进程来控制界面。
        const mainWindow = BrowserWindow.getFocusedWindow();
        if (mainWindow) {
            mainWindow.webContents.send("autoUpdate", info.version);
        }
        // dialog.showMessageBox({
        //     type: "info",
        //     title: "更新提示",
        //     message: "检测到新版本，是否下载？",
        //     buttons: ["是", "否"],
        // }).then(({ response }) => {
        //     if (response === 0) {
        //         autoUpdater.downloadUpdate();
        //     }
        // });
    }
    downloadUpdate() {
        autoUpdater.downloadUpdate();
    }
    downloaded() {
        log.info("update downloaded...");
        console.info("更新完毕，并进行安装");
        autoUpdater.quitAndInstall();
    }
    progress(process: ProcessType) {
        log.info("下载进度：", process.percent);
    }
}
export const updateTool = new UpdateTool();